/**
 * 🌍 登录页面国际化 Composable
 *
 * 提供统一的文本管理接口，支持动态语言切换
 */

import { ref, computed } from 'vue'
import { getLoginText, type LoginLocale, type LoginLocaleKey, defaultLoginLocale } from '@/locales/login'

// 全局语言状态
const currentLocale = ref<LoginLocaleKey>(defaultLoginLocale)

export function useLoginLocale() {
  /**
   * 获取当前语言环境
   */
  const locale = computed(() => currentLocale.value)

  /**
   * 获取完整的语言包
   */
  const localeData = computed((): LoginLocale => {
    return getLoginText(currentLocale.value) as LoginLocale
  })

  /**
   * 获取特定键的文本
   */
  const t = (key: string): string => {
    return getLoginText(currentLocale.value, key) as string
  }

  /**
   * 切换语言
   */
  const setLocale = (newLocale: LoginLocaleKey) => {
    currentLocale.value = newLocale
    // 可以在这里添加持久化逻辑，例如存储到 localStorage
    try {
      localStorage.setItem('login-locale', newLocale)
    } catch (error) {
      console.warn('Failed to save locale preference:', error)
    }
  }

  /**
   * 检查是否为特定语言
   */
  const isLocale = (checkLocale: LoginLocaleKey): boolean => {
    return currentLocale.value === checkLocale
  }

  /**
   * 获取可用语言列表
   */
  const availableLocales = computed(() => {
    return [
      { key: 'zh-CN' as LoginLocaleKey, name: '简体中文', flag: '🇨🇳' },
      { key: 'en-US' as LoginLocaleKey, name: 'English', flag: '🇺🇸' }
    ]
  })

  /**
   * 获取当前语言信息
   */
  const currentLocaleInfo = computed(() => {
    return availableLocales.value.find(loc => loc.key === currentLocale.value) || availableLocales.value[0]
  })

  /**
   * 从本地存储恢复语言设置
   */
  const restoreLocale = () => {
    try {
      const savedLocale = localStorage.getItem('login-locale') as LoginLocaleKey
      if (savedLocale && ['zh-CN', 'en-US'].includes(savedLocale)) {
        currentLocale.value = savedLocale
      }
    } catch (error) {
      console.warn('Failed to restore locale preference:', error)
    }
  }

  /**
   * 获取表单验证规则
   */
  const getValidationRules = () => {
    const texts = localeData.value.form

    return {
      username: [
        { required: true, message: texts.username.error.required, trigger: 'blur' }
      ],
      password: [
        { required: true, message: texts.password.error.required, trigger: 'blur' },
        { min: 6, message: texts.password.error.minLength, trigger: 'blur' }
      ]
    }
  }

  /**
   * 获取页面元数据
   */
  const getPageMeta = () => {
    const meta = localeData.value.meta
    return {
      title: localeData.value.title,
      description: meta.description,
      keywords: meta.keywords.join(', ')
    }
  }

  /**
   * 获取无障碍访问文本
   */
  const getAccessibilityTexts = () => {
    return localeData.value.accessibility
  }

  /**
   * 格式化消息（支持参数插值）
   */
  const formatMessage = (key: string, params?: Record<string, string | number>): string => {
    let message = t(key)

    if (params) {
      Object.entries(params).forEach(([param, value]) => {
        message = message.replace(new RegExp(`\\{${param}\\}`, 'g'), String(value))
      })
    }

    return message
  }

  return {
    // 状态
    locale,
    localeData,
    currentLocaleInfo,
    availableLocales,

    // 方法
    t,
    setLocale,
    isLocale,
    restoreLocale,

    // 便捷方法
    getValidationRules,
    getPageMeta,
    getAccessibilityTexts,
    formatMessage
  }
}

// 导出单例实例，用于全局使用
export const loginLocale = useLoginLocale()